import React, { memo, useEffect, useState } from 'react';
import { Popconfirm, Button, Tooltip, Modal } from 'antd';
import {
    CloseOutlined,
    ShareAltOutlined,
    StopOutlined,
    DeleteOutlined,
    LogoutOutlined
} from '@ant-design/icons';
import { useDrag } from 'react-dnd';
import './index.css';

const ImageCard = memo(
    ({
        id,
        imageUrl,
        title,
        position,
        animation,
        isShared = false,
        sharedCode = '',
        isOwner,
        useRelativePosition = false,
        onSelect,
        onDelete = () => {},
        onShare = () => {},
        onCancelShare = () => {}
    }) => {
        const [customColor, setCustomColor] = useState('');

        // 从localStorage获取自定义颜色并监听实时变化
        useEffect(() => {
            // 初始化时获取当前颜色
            const savedColor = localStorage.getItem('customColor');
            if (savedColor) {
                setCustomColor(savedColor);
            }

            // 监听localStorage变化（仅在不同窗口/标签页间有效）
            const handleStorageChange = (e) => {
                if (e.key === 'customColor') {
                    setCustomColor(e.newValue);
                }
            };

            // 监听自定义事件，用于捕获同一窗口内的主题颜色变化
            const handleThemeChange = (e) => {
                const newColor = e.detail;
                setCustomColor(newColor);
            };

            // 注册事件监听器
            window.addEventListener('storage', handleStorageChange);
            document.addEventListener('theme-color-change', handleThemeChange);

            return () => {
                window.removeEventListener('storage', handleStorageChange);
                document.removeEventListener('theme-color-change', handleThemeChange);
            };
        }, []);

        const [{ isDragging }, drag] = useDrag(
            () => ({
                type: 'image',
                item: () => ({ id, type: 'image' }),
                collect: (monitor) => ({
                    isDragging: !!monitor.isDragging()
                }),
                canDrag: !useRelativePosition
            }),
            [id, useRelativePosition]
        );

        const handleClick = (e) => {
            // 防止拖拽后触发点击事件
            if (!isDragging) {
                onSelect(id);
            }
        };

        const handleShareClick = (e) => {
            e.stopPropagation();
            onShare(id);
        };

        const handleCancelShareClick = (e) => {
            e.stopPropagation();
            onCancelShare(id);
        };

        // 使用useEffect来动态设置CSS变量
        useEffect(() => {
            if (customColor) {
                // 设置到组件元素上而不是全局，这样每个卡片实例都能独立设置颜色
                // 我们将在元素上直接应用这些颜色
                console.log('ImageCard: Theme color updated to', customColor);
            }
        }, [customColor]);

        // 计算按钮样式
        const shareButtonStyle = {
            backgroundColor: isShared ? undefined : customColor || 'var(--color-primary, #1890ff)'
        };

        const cancelShareButtonStyle = {
            color: customColor || 'var(--color-primary, #1890ff)',
            borderColor: customColor || 'var(--color-primary, #1890ff)'
        };

        const cancelShareHoverStyle = {
            backgroundColor: customColor || 'var(--color-primary, #1890ff)',
            color: 'white'
        };

        console.log('isOwner:', isOwner);

        // 根据模式选择样式
        const getCardStyle = () => {
            if (useRelativePosition) {
                return {
                    position: 'relative',
                    opacity: isDragging ? 0.5 : 1,
                    cursor: 'pointer',
                    zIndex: isDragging ? 1000 : 1,
                    willChange: 'transform, opacity',
                    backfaceVisibility: 'hidden',
                    transition: isDragging ? 'none' : 'all 0.3s',
                    contain: 'layout'
                };
            } else {
                return {
                    position: 'absolute',
                    transform: `translate3d(${position.x}px, ${position.y}px, 0)`,
                    opacity: isDragging ? 0.5 : 1,
                    cursor: 'move',
                    zIndex: isDragging ? 1000 : 1,
                    willChange: 'transform, opacity',
                    backfaceVisibility: 'hidden',
                    transition: isDragging ? 'none' : 'all 0.3s',
                    contain: 'layout'
                };
            }
        };

        return (
            <div
                ref={drag}
                className={`image-card ${isDragging ? 'dragging' : ''} ${animation || ''} ${useRelativePosition ? 'virtual-list-card' : ''}`}
                style={getCardStyle()}
                onClick={handleClick}
            >
                <img
                    src={imageUrl}
                    alt={title}
                    style={{
                        display: 'block',
                        width: '100%',
                        height: '150px',
                        objectFit: 'contain',
                        backgroundColor: '#ffffff',
                        backfaceVisibility: 'hidden',
                        transform: 'translateZ(0)'
                    }}
                    loading={useRelativePosition ? 'eager' : 'lazy'}
                    onError={(e) => {
                        e.target.onerror = null;
                        e.target.src = '/封面.jpg';
                    }}
                />
                <div className="title">
                    <span>{title || '未命名'}</span>
                    <div className="title-buttons">
                        {/* 取消分享按钮，仅对所有者显示 */}
                        {isOwner && (
                            <Tooltip title={isShared ? '取消分享' : '未分享'} placement="bottom">
                                <StopOutlined
                                  className="share-button"
                                  onClick={isShared ? handleCancelShareClick : undefined}
                                  
                                />
                            </Tooltip>
                        )}
                        {isOwner &&
                            (isShared ? (
                                <Tooltip title={`当前分享码: ${sharedCode}`} placement="bottom">
                                    <ShareAltOutlined
                                        className="share-button shared"
                                        onClick={(e) => e.stopPropagation()}
                                    />
                                </Tooltip>
                            ) : (
                                <Tooltip title="分享画布" placement="bottom">
                                    <ShareAltOutlined
                                        className="share-button"
                                        style={shareButtonStyle}
                                        onClick={handleShareClick}
                                    />
                                </Tooltip>
                            ))}
                    </div>
                </div>

                {/* 删除/退出按钮 */}
                <Popconfirm
                    title={isOwner ? '删除画布' : '退出协作'}
                    description={isOwner ? '确定要删除这个画布吗？' : '确定要退出此画布的协作吗？'}
                    onConfirm={(e) => {
                        e?.stopPropagation();
                        onDelete({
                            id,
                            isOwner,
                            title,
                            imageUrl,
                            isShared,
                            sharedCode
                        });
                    }}
                    onCancel={(e) => e?.stopPropagation()}
                    okText="确定"
                    cancelText="取消"
                >
                    {isOwner ? (
                        <DeleteOutlined
                            className="delete-button"
                            onClick={(e) => e.stopPropagation()}
                        />
                    ) : (
                        <LogoutOutlined
                            className="exit-button"
                            onClick={(e) => e.stopPropagation()}
                        />
                    )}
                </Popconfirm>
            </div>
        );
    }
);

export default ImageCard;
